const jsonServer = require("json-server");
const { initialize } = require("express-openapi");
const swaggerUi = require("swagger-ui-express");

const shellPath = process.cwd();
const router = jsonServer.router(`${shellPath}/db.json`);
require("dotenv").config({ path: `${shellPath}/.env` });

const app = jsonServer.create();

module.exports = (options) =>
  initialize({
    app,
    docsPath: "/api-docs",
    validateApiDoc: true,
    paths: "",
    ...options, // 合并自定义选项
    dependencies: {
      dbService: router.db,
      ...options.dependencies,
    },
    apiDoc: {
      ...options.apiDoc,
    },
    info: {
      ...options.info,
    },
  }).then(({ args }) => {
    const { apiDoc, app, docsPath } = args;
    const basePath = apiDoc.basePath;
    // swagger-ui
    app.use(
      "/api-documentation",
      swaggerUi.serve,
      swaggerUi.setup(null, {
        swaggerOptions: {
          url: `http://${process.env.HOST}:${process.env.PORT}${basePath}${docsPath}`,
        },
      })
    );

    // 业务路由
    app.use(basePath, router);

    // 启动服务器
    app.listen(process.env.PORT, process.env.HOST, () => {
      console.log("Server http://%s:%s", process.env.HOST, process.env.PORT);
      console.log(
        "Docs http://%s:%s/api-documentation",
        process.env.HOST,
        process.env.PORT
      );
    });
  });
